package com.whut.transportation;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.whut.transportation.adapter.ReasonAdapter;
import com.whut.transportation.adapter.ReasonAdapter.ViewHolder;
import com.whut.transportation.entity.AllReason;
import com.whut.transportation.entity.Message;
import com.whut.transportation.entity.Reason;
import com.whut.transportation.entity.TrainCheckInfo;
import com.whut.transportation.entity.TransInfo;
import com.whut.transportation.network.HttpManager;
import com.whut.transportation.network.HttpRequestVo;
import com.whut.transportation.parser.JSONParser;
import com.whut.transportation.ui.BaseActivity;
import com.whut.transportation.utils.Constant;

public class CarCheckSecondActivity extends BaseActivity {
	private TransInfo transinfo;// 运输信息

	private LinearLayout activity_car_check;
	private LinearLayout activity_car_check_normal;
	private View view_car_check_normal;
	private LinearLayout activity_car_check_error;
	private View view_car_check_error;
	private LinearLayout check_line1;

	private LinearLayout popupwindow;
	private View view_popupwindow;

	private RadioGroup car_check_radiogroup1;
	private RadioGroup car_check_fix;

	private RadioButton car_check_normal;
	private RadioButton car_check_error;
	private RadioButton fix_radioButton1;
	private RadioButton fix_radioButton2;

	private CheckBox checkBox1;
	private CheckBox checkBox2;

	private LinearLayout car_check_line1;
	private TextView car_check_line2;

	private EditText car_check_otherReason;

	private Button success_submit;
	private Button error_submit;

	private SharedPreferences preferences;

	private boolean flag = false;
	private List<Reason> reasons;
	private TrainCheckInfo trainCheckInfo;
	private Reason reasonEntity;

	private int type;
	private boolean checkedFirst = false;
	private boolean checkedSecond = false;
	private Button reason;
	private TextView reasonList;
	private Button submit;
	private Button cancel;
	private ListView list;
	private PopupWindow window;
	private ReasonAdapter reasonAdapter;
	private List rId = new ArrayList();

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void loadViewLayout() {
		setContentView(R.layout.activity_car_check);
		view_car_check_normal = View.inflate(mContext,R.layout.activity_car_check_normal, null);
		view_car_check_error = View.inflate(mContext,R.layout.activity_car_check_error, null);
		view_popupwindow = View.inflate(mContext, R.layout.popupwindow, null);
		Intent intent = getIntent();
		transinfo = (TransInfo) intent.getSerializableExtra("transinfo");
		type = transinfo.getType();
		checkedFirst = true;
		// checkedSecond = intent.getBooleanExtra("check", false);
		preferences = getSharedPreferences("userId", Context.MODE_PRIVATE);
		setTitleBarView(true, transinfo.getTrainNumber() + transinfo.getTrain()+ "检查", -1, true);
	}

	@Override
	protected void findViewById() {
		activity_car_check = (LinearLayout) findViewById(R.id.activity_car_check);
		activity_car_check_normal = (LinearLayout) findViewById(R.id.activity_car_check_normal);
		activity_car_check_error = (LinearLayout) findViewById(R.id.activity_car_check_error);
		popupwindow = (LinearLayout) findViewById(R.id.popupwindow);

		car_check_radiogroup1 = (RadioGroup) findViewById(R.id.car_check_radiogroup1);
		car_check_normal = (RadioButton) findViewById(R.id.car_check_normal);
		car_check_error = (RadioButton) findViewById(R.id.car_check_error);
		/* activity_car_check_normal */
		success_submit = (Button) view_car_check_normal.findViewById(R.id.success_submit);
		/* activity_car_check_error */
		car_check_fix = (RadioGroup) view_car_check_error.findViewById(R.id.car_check_fix);
		fix_radioButton1 = (RadioButton) view_car_check_error.findViewById(R.id.fix_radioButton1);
		fix_radioButton2 = (RadioButton) view_car_check_error.findViewById(R.id.fix_radioButton2);

		checkBox1 = (CheckBox) view_car_check_error.findViewById(R.id.checkBox1);
		checkBox2 = (CheckBox) view_car_check_error.findViewById(R.id.checkBox2);

		reason = (Button) view_car_check_error.findViewById(R.id.reason);
		reasonList = (TextView) view_car_check_error.findViewById(R.id.textView1);
		car_check_line1 = (LinearLayout) view_car_check_error.findViewById(R.id.car_check_line1);
		car_check_line2 = (TextView) view_car_check_error.findViewById(R.id.car_check_line2);
		car_check_otherReason = (EditText) view_car_check_error.findViewById(R.id.car_check_otherReason);
		error_submit = (Button) view_car_check_error.findViewById(R.id.error_submit);
		list = (ListView) view_popupwindow.findViewById(R.id.lv);
		submit = (Button) view_popupwindow.findViewById(R.id.submit);
		cancel = (Button) view_popupwindow.findViewById(R.id.cancel);
	}

	@Override
	protected void afterFindViewId() {
	}

	@Override
	protected void processLogic() {
		findTrianCheckInfo();
		getAllReason();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.success_submit:
			successSubmit();
			break;
		case R.id.error_submit:
			errorSubmit();
			break;
		case R.id.reason:
			toDialog();
		default:
			break;
		}
		super.onClick(v);
	}

	private void errorSubmit() {
		String description = car_check_otherReason.getText().toString().trim()
				+ reasonList.getText().toString().trim();
		String checkResult = "";
		if (fix_radioButton1.isChecked())
			checkResult = "1";
		else
			checkResult = "2";
		if (checkedFirst) {// 第一次提交插入
			insertIntoTrainCheckInfo(checkResult, description, null);
			checkedFirst = false;
		} else {
			updateTrainCheckInfo(checkResult, description);
		}
		Intent uploadPhone = new Intent(CarCheckSecondActivity.this, UploadPhoneActivity.class);
		uploadPhone.putExtra("transinfo", transinfo);
		uploadPhone.putExtra("checkResult", checkResult);
		startActivity(uploadPhone);
		finish();
	}
	/**
	 * 没有问题直接
	 */
	private void successSubmit() {
		if (checkedFirst) {// 第一次提交插入
			insertIntoTrainCheckInfo("0", null, null);
			checkedFirst = false;
		} else {
			updateTrainCheckInfo("0", null);
		}
		Intent entruckIntent = new Intent(CarCheckSecondActivity.this, HomeActivity.class);
		startActivity(entruckIntent);
		finish();
	}

	/**
	 * 将检查信息插入车辆检查信息表
	 * @param checkTime
	 * @param checkResult
	 * @param description
	 * @param reasonId
	 */
	private void insertIntoTrainCheckInfo(String checkResult,String description, String reasonId) {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.INSERT_TRAIN_CHECK_SECFOND_INFO;
		vo.context = mContext;
		vo.parser = new JSONParser(Message.class);
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("id", transinfo.getId());
		req.put("jiancha.shunhao", transinfo.getNumber());
		req.put("jiancha.description", description);
		req.put("jiancha.daima", transinfo.getDaima());
		req.put("jiancha.chezhong", transinfo.getTrain());
		req.put("jiancha.chehao", transinfo.getTrainNumber());
		req.put("jiancha.account",preferences.getString("account", null));
		req.put("checkResult", checkResult);
		req.put("type", String.valueOf(transinfo.getType()));
		vo.requestDataMap = req;
		getDataFromServer(HttpManager.POST_MOTHOD, vo,
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
						showProgressDialog(getResources().getString(R.string.loading_content));
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(
							HashMap<String, Object> paramObject,
							boolean paramBoolean) {
						Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}
	/**
	 * 更新车辆检查信息表
	 * @param checkTime
	 * @param checkResult
	 * @param description
	 */
	private void updateTrainCheckInfo(String checkResult,String description) {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.UPDATE_TRAIN_CHECK_SECOND_INFO;
		vo.context = mContext;
		vo.parser = new JSONParser(Message.class);
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("type", String.valueOf(transinfo.getType()));
		req.put("id", transinfo.getId());
		req.put("jiancha.description", description);
		req.put("jiancha.chezhong", transinfo.getTrain());
		req.put("jiancha.chehao", transinfo.getTrainNumber());
		req.put("checkResult", checkResult);
		vo.requestDataMap = req;
		getDataFromServer(HttpManager.POST_MOTHOD, vo,
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
						showProgressDialog(getResources().getString(R.string.loading_content));
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(
							HashMap<String, Object> paramObject,
							boolean paramBoolean) {
						Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}
	/**
	 * 进入查找列车的检查信息
	 */
	private void findTrianCheckInfo() {
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.FIND_ONE_TRAIN_CHECK_SECOND_INFO;
		vo.context = mContext;
		HashMap<String, String> req = new HashMap<String, String>();
		req.put("id", transinfo.getId());
		req.put("type", String.valueOf(transinfo.getType()));
		vo.requestDataMap = req;
		vo.parser = new JSONParser(TrainCheckInfo.class);
		getDataFromServer(HttpManager.POST_MOTHOD, vo,
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(HashMap<String, Object> paramObject,boolean paramBoolean) {
						trainCheckInfo = (TrainCheckInfo) paramObject.get("result");
						transinfo.setComplete(trainCheckInfo.getComplete());
						transinfo.setFlag(trainCheckInfo.getFlag());
						if (trainCheckInfo.getMessage() == 1) {
							checkedFirst = false;
							transinfo.setComplete(trainCheckInfo.getComplete());
							transinfo.setFlag(trainCheckInfo.getFlag());
							if (trainCheckInfo.getCheckResult() == 1) {
								car_check_error.setChecked(true);
								fix_radioButton1.setChecked(true);
								reasonList.setText(trainCheckInfo.getDescription());
								car_check_otherReason.setText("");
							} else if (trainCheckInfo.getCheckResult() == 2) {
								car_check_error.setChecked(true);
								fix_radioButton2.setChecked(true);
								reasonList.setText(trainCheckInfo.getDescription());
								car_check_otherReason.setText("");
							}
						}
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}

	/**
	 * 查询车辆损坏的所有原因
	 */
	private void getAllReason() {
		reasons = new ArrayList<Reason>();
		HttpRequestVo vo = new HttpRequestVo();
		vo.requestUrl = Constant.FIND_REASON_ENTRUCK;
		vo.context = mContext;
		vo.requestDataMap = null;
		vo.parser = new JSONParser(AllReason.class);
		getDataFromServer(HttpManager.POST_MOTHOD, vo,
				new DataCallback<HashMap<String, Object>>() {
					@Override
					public void onStart() {
					}
					@Override
					public void onFailed() {
						showNetErrorDialog();
					}
					@Override
					public void processData(
							HashMap<String, Object> paramObject,
							boolean paramBoolean) {
						AllReason allReason = (AllReason) paramObject
								.get("result");
						reasons.addAll(allReason.ListReason);

						for (Reason reason : allReason.ListReason)
							if (list.getAdapter() == null) {
								reasonAdapter = new ReasonAdapter(mContext,
										reasons);
								list.setAdapter(reasonAdapter);
								list.setItemsCanFocus(false);
								list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
							} else {
								reasonAdapter.notifyDataSetChanged();
							}
					}
					@Override
					public void onFinish() {
						closeProgressDialog();
					}
				});
	}

	@Override
	protected void setListener() {
		success_submit.setOnClickListener(this);
		error_submit.setOnClickListener(this);
		reason.setOnClickListener(this);
		submit.setOnClickListener(submitListener);
		cancel.setOnClickListener(cancelListener);
		list.setOnItemClickListener(listClickListener);
		car_check_radiogroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						int radioButtonId = group.getCheckedRadioButtonId();
						if (radioButtonId == R.id.car_check_normal) {
							activity_car_check.removeView(view_car_check_error);
							activity_car_check.addView(view_car_check_normal);
						} else {
							activity_car_check.removeView(view_car_check_normal);
							activity_car_check.addView(view_car_check_error);
						}
					}
				});
	}

	OnClickListener bPop = new OnClickListener() {
		@Override
		public void onClick(View v) {
			popAwindow(v);
		}
	};

	private void popAwindow(View parent) {
		if (window == null) {
			view_popupwindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.rounded_corners_pop));
			window = new PopupWindow(view_popupwindow, 450, 260);
		}

		// 设置整个popupwindow的样式。
		window.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.rounded_corners_pop));
		// 使窗口里面的空间显示其相应的效果，比较点击button时背景颜色改变。
		// 如果为false点击相关的空间表面上没有反应，但事件是可以监听到的。
		// listview的话就没有了作用。
		window.setFocusable(true);// 如果不设置setFocusable为true，popupwindow里面是获取不到焦点的，那么如果popupwindow里面有输入框等的话就无法输入。
		window.update();
		// window.showAtLocation(parent, Gravity.CENTER_VERTICAL, 0, 0);
		window.showAsDropDown(reason, 0, 0);
	}

	OnItemClickListener listClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			ViewHolder vHollder = (ViewHolder) view.getTag();
			// 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
			vHollder.cBox.toggle();
			ReasonAdapter.isSelected.put(position, vHollder.cBox.isChecked());
			// values.add(vHollder.cBox.getText().toString());
		}
	};
	OnClickListener submitListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			List<String> values = new ArrayList<String>();
			for (int i = 0; i < list.getCount(); i++) {
				Reason reason = reasons.get(i);
				if (ReasonAdapter.isSelected.get(i)) {
					ViewHolder vHollder = (ViewHolder) list.getChildAt(i).getTag();
					values.add(vHollder.title.getText().toString());
					rId.add(reason.getReasonId());
				}
			}
			// 这儿可以写提交数据的代码。
			reasonList.setText(values.toString());
			/*
			 * for(int i=0;i<rId.size();i++){
			 * insertReasonCheckTrain(String.valueOf(rId.get(i))); }
			 */
			// Toast.makeText(MainActivity.this, values.toString(), 1).show();
			closeWindow();
		}
	};

	OnClickListener cancelListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			closeWindow();
		}
	};

	private void closeWindow() {

		// 将每个checkbox的标记改为false，以便下次弹出window时是初始的状态。
		for (int j = 0; j < ReasonAdapter.isSelected.size(); j++) {
			if (ReasonAdapter.isSelected.get(j)) {
				ReasonAdapter.isSelected.put(j, false);
				ViewHolder vHollder = (ViewHolder) list.getChildAt(j).getTag();
				vHollder.cBox.setChecked(false);
			}
		}
		// 提交数据时关闭popupwindow。
		if (window != null) {
			window.dismiss();
		}
	}

	@Override
	protected void getDataAgain() {

	}
	
	public void toDialog(){
		Intent intent = new Intent();
		intent.setClass(CarCheckSecondActivity.this, DialogActivity.class);
		startActivityForResult(intent, 1);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		reasonList.setText(data.getExtras().getString("resultValue"));
	}

}
